package com.guangbao.utils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.guanbao.entity.User;

public class TokenUtil {
	private static final String  SECRETS = "123456";

	/**
	 * 创建token
	 * @param user
	 * @return
	 */
	public static String createJWT(User user) {

		Map<String, Object> map = new HashMap<>();
		Calendar instance = Calendar.getInstance();
		instance.add(Calendar.HOUR, 2);
		JWTCreator.Builder builder =JWT.create();
		String token = builder.withHeader(map)// 添加头部
				.withClaim("id", user.getId())// 添加payload
				.withClaim("username", user.getUsername()).withExpiresAt(instance.getTime())// 设置过期时间
				.sign(Algorithm.HMAC256(SECRETS));// 设置签名 密钥
		return token;
	}

	/**
	 * 验证token
	 * @param token
	 * @return
	 */
	public static User verify(String token) {
		try {
			// 创建验证对象,这里使用的加密算法和密钥必须与生成TOKEN时的相同否则无法验证
			JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRETS)).build();
			// 验证JWT
			DecodedJWT decodedJWT = jwtVerifier.verify(token);
			// 获取JWT中的数据,注意数据类型一定要与添加进去的数据类型一致,否则取不到数据
			User user = new User();
			user.setId(decodedJWT.getClaim("id").asInt());
			user.setUsername(decodedJWT.getClaim("username").asString());
			System.out.println(decodedJWT.getExpiresAt());
			return user;
		} catch (Exception err) {
		}
		return null;
	}

}
